package xin.nick.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xin.nick.domain.ProjectBO;
import xin.nick.service.ProjectService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 生产任务计划
 * @author Nick
 * @since 2023/4/14
 */
@Slf4j
@RestController
@RequestMapping("/api/project")
@RequiredArgsConstructor
public class ProjectController {

    private final ProjectService projectService;

    @GetMapping("/getAllList")
    public List<String> getAllList(String username) {
        return Arrays.asList(username + "任务一", "任务二", username + "任务三");
    }

    @GetMapping("/getProjectListByUsername")
    public List<String> getProjectListByUsername(String username) {
        return projectService.getProjectListByUsername(username);
    }

    @GetMapping("/exportProjectList")
    public void exportProjectList(HttpServletResponse response) throws IOException {

        // 准备导出的项目列表
        List<ProjectBO> dataList = new ArrayList<>();

        // 往列表里面放项目，放了十个
        for (int i = 0; i < 10; i++) {
            ProjectBO projectBO = new ProjectBO();
            projectBO.setProjectName("多多的项目" + i);
            projectBO.setStartTime(LocalDateTime.now());
            projectBO.setEndTime(LocalDateTime.now());
            dataList.add(projectBO);
        }

        // 准备设置好response，用来返回 excel 数据给 前端的
        String fileName = "duoduo.xls";
        response.setContentType("application/ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();

        // 使用 EasyExcel 来进行将项目列表导出给前端
        EasyExcel.write(outputStream, ProjectBO.class).sheet().doWrite(dataList);

    }

    @PostMapping("/importProjectList")
    public void importProjectList(MultipartFile file) throws Exception {

        EasyExcel.read(file.getInputStream(), ProjectBO.class, new PageReadListener<ProjectBO>(dataList -> {
            for (ProjectBO demoData : dataList) {
                log.info("读取到一条数据{}", JSON.toJSONString(demoData));
            }
        })).sheet().doRead();

    }

}
